package com.jianggy.proxy;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author jianggy
 * @time 2018年9月23日 下午11:01:38
 * @description
 */
public class UserDaoImpl implements UserDao {
	public static Connection connection = null;
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://192.168.231.6:3306/test", "root", "NongDa-2017");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public User getUser(long id) {
		User user = new User();
		try {
			System.out.println("执行查询");
			PreparedStatement st = connection.prepareStatement("select * from user where id=?");
			st.setLong(0, id);
			ResultSet rs = st.executeQuery();
			while (rs.next()) {
				user.setId(rs.getLong(1));
				user.setName(rs.getString(2));
				user.setAddress(rs.getString(3));
				user.setSex(rs.getInt(4));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	@Override
	public void insertUser(User user) {
		try {
			System.out.println("插入用户");
			PreparedStatement st = connection.prepareStatement("insert into user(id,name,sex,address) values(?,?,?,?)");
			st.setLong(1, user.getId());
			st.setString(2, user.getName());
			st.setInt(3, user.getSex());
			st.setString(4, user.getAddress());
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void deleteUser(int id) {
		try {
			System.out.println("删除用户");
			PreparedStatement st = connection.prepareStatement("delete from user where id=id");
			st.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void updateUser(User user) {
		try {
			System.out.println("更新用户");
			PreparedStatement st = connection.prepareStatement("update user set name=? where id=?");
			st.setLong(1, user.getId());
			st.setString(2, user.getName());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
